package com.shuo.nio.machine;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Random;

/**
 * @description NIO8的例程: 客户端发一个数到服务器, 延时5s, 再发一个数到服务器
 *                         (如果服务器端是阻塞式的(同步), 则这5s会浪费掉, 如果服务器端用异步则会用这5s去干其他事, 不浪费 )
 * @author linshuo
 *
 */
public class EpollClient {

    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress( "127.0.0.1", 8000));
            ByteBuffer writeBuffer = ByteBuffer.allocate(32);
            ByteBuffer readbuffer = ByteBuffer.allocate(32);
            byte[] buf = new byte[32];
            Random r = new Random();
            int d = 0;
            d = r.nextInt(1000);
            System.out.println(d);
            writeBuffer.put(String.valueOf(d).getBytes());
            socketChannel.write(writeBuffer);
            socketChannel.read(readbuffer);             //这句是阻塞的?
            readbuffer.flip();
            System.out.println(new String(readbuffer.array()));
            
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            writeBuffer.clear();
            d= r.nextInt(10);
            System.out.println(d);
            writeBuffer.put(String.valueOf(d).getBytes());
            writeBuffer.flip();
            socketChannel.write(writeBuffer);
            
            readbuffer.clear();
            socketChannel.read(readbuffer);
            readbuffer.flip();
            readbuffer.get(buf, 0, readbuffer.remaining());
            System.out.println(new String(buf));
            
            socketChannel.close();
        } catch (Exception e) {
        }
    }
}
